package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"week3-dev/cache"
	"week3-dev/model"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	anchor := c.PostForm("anchor")

	if title == "" || content == "" || anchor == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}

	data := model.Article{
		Title:   title,
		Content: content,
		Anchor:  anchor,
	}

	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "4"))
	offset := (page - 1) * size

	var article []model.Article
	redis_key := "article_list" + strconv.Itoa(page)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if redisData == "" {
		model.DB.Offset(offset).Limit(size).Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &article)
	}

	var total int64
	model.DB.Model(&model.Article{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "添加成功",
		"data":  article,
		"total": total,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")

	var article []model.Article
	redis_key := "article_list" + id
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if redisData == "" {
		model.DB.Where("id", id).Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &article)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": article,
	})
	return
}

func Del(c *gin.Context) {
	id := c.PostForm("id")

	var article model.Article
	err := model.DB.Where("id", id).Delete(&article).Error

	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
